package com.h3bpm.starcharge.service.impl.k3c;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.starcharge.common.bean.RetResponse;
import com.h3bpm.starcharge.common.bean.RetResult;
import com.h3bpm.starcharge.common.uitl.HttpUtil;
import com.h3bpm.starcharge.ret.k3c.K3cBase;
import com.h3bpm.starcharge.service.k3c.K3cService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * K3cServiceImpl
 *
 * @author LLongAgo
 * @date 2019/3/22
 * @since 1.0.0
 */
@Service
public class K3cServiceImpl implements K3cService {

    /**
     * 构造登录参数
     *
     * @param dbid     账套id
     * @param userName 用户名
     * @param password 密码
     * @param lang     语言
     * @return String
     */
    @Override
    public String buildLogin(String dbid, String userName, String password, int lang) {
        Map<String, Object> param = new HashMap<>(8);
        param.put("acctID", dbid);
        param.put("username", userName);
        param.put("password", password);
        param.put("lcid", lang);
        return JSON.toJSONString(param);
    }

    /**
     * 构造提交、反审核、审核参数
     *
     * @param formId  表单id
     * @param ids     id
     * @param numbers 编码 多个编码以,分隔
     * @param flags   审核标示 多个以,分隔 和编码一一对应
     * @return String
     */
    @Override
    public String buildParam(String formId, String ids, String numbers, String flags) {
        JSONObject jsonObject = new JSONObject();
        JSONObject param = new JSONObject();
        if (flags != null) {
            String[] arrFlag = flags.split(",");
            param.put("InterationFlags", arrFlag);
        }
        if (ids != null) {
            param.put("Ids", ids);
        }
        if (numbers != null) {
            String[] arrNumber = numbers.split(",");
            param.put("Numbers", arrNumber);
        }
        jsonObject.put("formid", formId);
        jsonObject.put("data", param);
        return JSON.toJSONString(jsonObject);
    }

    /**
     * 构造查看参数
     *
     * @param formId 表单id
     * @param number 编码
     * @param id     id
     * @return String
     */
    @Override
    public String buildViewParam(String formId, String number, String id) {
        JSONObject jsonObject = new JSONObject();
        JSONObject param = new JSONObject();
        if (number != null) {
            param.put("Number", number);
        }
        if (number != null) {
            param.put("Id", id);
        }
        jsonObject.put("formid", formId);
        jsonObject.put("data", param);
        return JSON.toJSONString(jsonObject);
    }

    /**
     * 构造分配参数
     *
     * @param formId 表单id
     * @param orgId  分配组织id
     * @param id     id
     * @return String
     */
    @Override
    public String buildAllocateParam(String formId, String orgId, String id) {
        JSONObject jsonObject = new JSONObject();
        JSONObject param = new JSONObject();
        param.put("PkIds", id);
        param.put("TOrgIds", orgId);
        param.put("IsAutoSubmitAndAudit", "true");
        jsonObject.put("formid", formId);
        jsonObject.put("data", param);
        return JSON.toJSONString(jsonObject);
    }

    /**
     * 金蝶登录接口
     *
     * @param url     接口地址
     * @param content 查询参数
     */
    @Override
    public RetResult login(String url, String content) {
        ResponseEntity<String> responseEntity = HttpUtil.httpPost(url, content);
        //获取登录cookie
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            if (responseEntity.getBody().contains("\"LoginResultType\":1")) {
                String loginCookie = "";
                Set<String> keys = responseEntity.getHeaders().keySet();
                for (String key : keys) {
                    if ("Set-Cookie".equalsIgnoreCase(key)) {
                        List<String> cookies = responseEntity.getHeaders().get(key);
                        for (String cookie : cookies) {
                            if (cookie.startsWith("kdservice-sessionid")) {
                                loginCookie = cookie;
                                break;
                            }
                        }
                    }
                }
                Map<String, Object> map = new HashMap<>(4);
                map.put("cookie", loginCookie);
                return RetResponse.makeOKRsp(map);
            } else {
                Map<String, Object> result = JSON.parseObject(responseEntity.getBody());
                return RetResponse.makeErrRsp(result.get("Message").toString());
            }
        } else {
            return RetResponse.makeErrRsp("登录失败!");
        }
    }

    /**
     * 保存接口
     *
     * @param url     接口地址
     * @param cookie  登录cookie
     * @param content json格式参数
     */
    @Override
    @SuppressWarnings("unchecked")
    public RetResult save(String url, String cookie, String content) {
        Map<String, Object> header = new HashMap<>(16);
        header.put("Cookie", cookie);
        String result = HttpUtil.httpPost(url, header, content);
        JSONObject jsonObject = JSON.parseObject(result);
        Map<String, Object> map = (Map<String, Object>) jsonObject.get("Result");
        Map<String, Object> responseStatus = (Map<String, Object>) map.get("ResponseStatus");
        Boolean isSuccess = (Boolean) responseStatus.get("IsSuccess");
        if (isSuccess) {
            JSONArray jsonArray = jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus").getJSONArray("SuccessEntitys");
            JSONObject row;
            StringBuilder ids = new StringBuilder();
            StringBuilder numbers = new StringBuilder();
            for (int i = 0; i < jsonArray.size(); i++) {
                row = jsonArray.getJSONObject(i);
                ids.append(row.get("Id")).append(",");
                numbers.append(row.get("Number")).append(",");
            }
            String id = ids.toString();
            String number = numbers.toString();
            K3cBase k3cBase = new K3cBase(id.substring(0, id.length() - 1));
            k3cBase.setNumber(number.substring(0, number.length() - 1));
            return RetResponse.makeOKRsp(k3cBase);
        } else {
            List<Map<String, Object>> errors = (List<Map<String, Object>>) responseStatus.get("Errors");
            return RetResponse.makeErrRsp(JSON.toJSONString(errors));
        }
    }
}